<template>
  <div>
    <!-- 1.表格数据-->
    <el-table :data="tableData"
              style="width: 100%;margin-bottom: 20px;"
              row-key="name"
              border
              default-expand-all
              :tree-props="{ children: 'permissions', hasChildren: 'hasChildren' }">
      <el-table-column
          label="名称"
          width="180">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="描述"
          width="180">
        <template slot-scope="{ row }">
          <span v-if="!row.parentId">{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="menuType" label="菜单类型" width="100">
        <template slot-scope="{ row }">
          <el-tag v-if="row.parentId" type="success">菜单</el-tag>
          <el-tag v-else type="danger">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope" v-if="!scope.row.parentId">
          <el-switch
              v-model="scope.row.status"
              :active-value="0"
              :inactive-value="1"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="updatePermissionStatus(scope.row)"
          ></el-switch>
          <span>{{ scope.row.status === 0 ? '开启' : '禁用' }}</span>
        </template>
        <template slot-scope="scope" v-else>
          <!-- 空模板，不显示状态信息 -->
        </template>
      </el-table-column>

      <el-table-column prop="createdAt" label="创建时间" width="170" sortable>
        <template slot-scope="scope">
          {{ scope.row.createdAt | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="300"
          align="center">
        <template slot-scope="scope">
          <template v-if="!scope.row.parentId">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">
              <i class="el-icon-edit"></i>
              编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">
              <i class="el-icon-delete"></i>
              删除
            </el-button>
          </template>

          <!--如果parentId存在就显示新增权限-->
          <template v-if="scope.row.parentId">
            <el-button type="primary" size="mini" @click="handleAdd(scope.row)">
              <i class="el-icon-setting"></i>
              新增权限
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>


    <!-- 2.模态框-->
    <!--    2.1 add-->
    <el-dialog :visible.sync="showAddModal" title="新增" width="30%" custom-class="my-dialog">
      <el-form ref="formRef" :model="newPerForm" :rules="rules" label-width="80px">
        <el-form-item label="权限名称" prop="name" required>
          <el-input v-model="newPerForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description" required>
          <el-input v-model="newPerForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="showAddModal = false">取消</el-button>
        <el-button type="primary" @click="saveNewPerForm">保存</el-button>
      </div>
    </el-dialog>

    <!--    2.2 编辑-->
    <el-dialog :visible.sync="showEditModal" title="新增" width="30%" custom-class="my-dialog">
      <el-form ref="formRef" :model="perEditForm" :rules="rules" label-width="80px">
        <el-form-item label="权限名称" prop="name" required>
          <el-input v-model="perEditForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description" required>
          <el-input v-model="perEditForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="showEditModal = false">取消</el-button>
        <el-button type="primary" @click="savePerEditForm">保存</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
import {MessageBox} from "element-ui";

export default {
  data() {
    return {
      perEditForm: {},
      menuId: null,
      tableData: [],
      showAddModal: false,
      newPerForm: {},
      showEditModal: false,
      rules: {
        name: [
          {required: true, message: '权限名称不能为空', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '描述不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getMenusAndPer();
  },
  // 方法
  methods: {
    async updatePermissionStatus(id) {
      const url = `/community/permission/updatePermissionStatus`;
      await this.$http.post(url,id);

      await this.$message.success("操作成功")
    },

    async handleDelete(id) {
      MessageBox.confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const url = `/community/permission/handleDelete/${id}`;
        const response = await this.$http.post(url);
        this.$message.success('删除成功');
        await this.getMenusAndPer();

      }).catch(() => {
        // 取消删除操作 or 错误处理
        this.$message.error('已取消操作');
      });
    },

    async savePerEditForm() {

      const url = `/community/permission/savePerEditForm`;
      const response = await this.$http.post(url, this.perEditForm);

      await this.getMenusAndPer();
      this.showEditModal = false;

      this.$message.success("操作成功")

    },

    async handleEdit(row) {
      this.perEditForm = row;
      this.showEditModal = true;
    },


    // 保存子权限
    async saveNewPerForm() {
      try {
        const isFormValid = await this.$refs.formRef.validate();
        if (!isFormValid) {
          return false; // 表单校验失败，不执行后续操作
        }
        const response = await this.$http.post(`/community/permission/saveNewPerForm/${this.menuId}`, this.newPerForm);
        if (response.status === 200) {
          this.$message.success("操作成功");
          this.showAddModal = false; // 可以在这里关闭模态框
        }
      } catch (error) {
        this.$message.error("操作失败");
      }
    },


    /**
     * 展示权限 的模态框,
     *  1.插入一条权限
     *  2.菜单权限表插入一条数据,父级菜单和子权限,就是刚刚插入的那个新的权限
     * @returns {Promise<void>}
     */
    async handleAdd(row) {
      this.menuId = row.id;
      this.showAddModal = true;
    },

    // 刷新页面 ,加载数据在tableData
    async getMenusAndPer() {
      const url = "/community/permission/getMenusAndPer";
      const response = await this.$http.post(url);

      this.tableData = response.data
    },
  }
}
</script>